package com.alibaba.cola.demo.command.query;

import com.alibaba.cola.core.command.Command;
import com.alibaba.cola.core.command.CommandExecutorI;
import com.alibaba.cola.core.dto.Response;
import com.alibaba.cola.demo.common.Result;
import com.alibaba.cola.demo.domain.Product;
import com.alibaba.cola.demo.domain.ProductExample;
import com.alibaba.cola.demo.dto.ProductDto;
import com.alibaba.cola.demo.dto.ProductQry;
import com.alibaba.cola.demo.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Command
public class ProductQryExe implements CommandExecutorI<Response, ProductQry> {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Result<List<ProductDto>> execute(ProductQry cmd) {
        ProductExample example = new ProductExample();
        example.createCriteria().andNameEqualTo(cmd.getName());
        List<Product> products = productMapper.selectByExample(example);

        List<ProductDto> productDtoList = new ArrayList<>();
        products.forEach(product -> {
            ProductDto productDto = new ProductDto();
            productDto.setId(product.getId());
            productDto.setName(product.getName());
            productDto.setPrice(product.getPrice());
            productDto.setCount(product.getCount());
            productDtoList.add(productDto);
        });
        return Result.SUCCESS(productDtoList);
    }
}
